package com.my.admin.util;

import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.fdfs.MetaData;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;

@Component
public class FastDFSUtil {

    @Autowired
    private FastFileStorageClient client;

    /**
     * 上传
     * @param file
     * @return
     */
    public StorePath upload(MultipartFile file) {
        Set<MetaData> metaData = new HashSet<>();
        metaData.add(new MetaData("author", "fastdfs"));
        metaData.add(new MetaData("description", file.getOriginalFilename()));
        StorePath path = null;
        try {
            path = client.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return path;
    }

    /**
     * 删除
     * @param path
     */
    public void delete(String path) {
        client.deleteFile(path);
    }

    /**
     * 删除
     * @param group
     * @param path
     */
    public void delete(String group, String path) {
        client.deleteFile(group, path);
    }

    /**
     *
     * @param path 文件路径
     * @param fileName 下载的文件名
     * @param response
     */
    public void download(String path, String fileName, HttpServletResponse response) {
        StorePath storePath = StorePath.parseFromUrl(path);
        if(StrUtil.isBlank(fileName)) {
            fileName = FilenameUtils.getName(storePath.getPath());
        }
        byte[] bytes = client.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
        response.reset();
        response.setContentType("applicatoin/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
